﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using ControlYSeguimiento.Domain;
using ControlYSeguimiento.Logging;
using System.Net.Mail;

namespace ControlYSeguimiento_Web_App.Mailing
{
    public partial class Mailing : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["prospectToMail"];
            if (cookie != null)
            {
                TextBoxProspectName.Text = cookie["prospectUserName"];
                TextBoxMail.Text = cookie["prospectMail"];

                cookie = new HttpCookie("prospectToMail");
                cookie.Values.Add("prospectUserName", String.Empty);
                cookie.Values.Add("prospectMail", String.Empty);
                cookie.Expires = DateTime.Now.AddHours(-3);
                Response.Cookies.Add(cookie);
                Request.Cookies.Add(cookie);

            }

        }

        private bool SendMail(string addressee, string subject)
        {
            bool boolResult = false;
            string smtpAddress = Facade.Instance.GetSmtpAddress();
            string smtpPort = Facade.Instance.GetSmtpPort();
            string smtpSSLEnabled = Facade.Instance.GetSmtpSSLEnabled();
            string smtpUser = Facade.Instance.GetSmtpUser();
            string smtpPassword = Facade.Instance.GetSmtpPassword();
            string smtpSenderAddress = Facade.Instance.GetSenderAddress();



            try
            {
                Logger.Instance.Info(this,"Preparando email a " + addressee + ". Asunto " + subject);

                using (SmtpClient client = new SmtpClient(smtpAddress, Convert.ToInt32(smtpPort)))
                {
                    Logger.Instance.Info(this, "Conectado a " + smtpAddress + " (" + smtpPort + ") - SSL=" + smtpSSLEnabled + ". Usuario: " + smtpUser);
                    client.EnableSsl = Convert.ToBoolean(smtpSSLEnabled);
                    client.UseDefaultCredentials = false;
                    client.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPassword);

                    client.DeliveryMethod = SmtpDeliveryMethod.Network;


                    using (MailMessage message = new MailMessage(smtpSenderAddress, addressee, subject, Facade.Instance.GetHtmlBodyMail(TextBoxMail.Text, TextBoxPassword.Text, DDLMobilePlatform.SelectedValue)))
                    {
                        message.Priority = MailPriority.High;                       
                        message.BodyEncoding = message.SubjectEncoding = System.Text.Encoding.UTF8;
                        message.IsBodyHtml = true;
                        message.Bcc.Add(new MailAddress("controlesyseguimiento@gmail.com"));

                        Logger.Instance.Info(this, "Enviando mail ...");
                        client.Send(message);
                        boolResult = true;
                    }

                    
                }

              

                

                //IMail email = Mail
                //.Html(Facade.Instance.GetHtmlBodyMail(TextBoxMail.Text, TextBoxPassword.Text, DDLMobilePlatform.SelectedValue))
                //.To(addressee)
                //.Bcc("controlesyseguimiento@gmail.com")
                //.From(smtpSenderAddress)
                //.Subject(subject)
                //.Create();



                //using (Smtp smtp = new Smtp())
                //{                    
                //    Logger.Instance.Info(this,"Conectando a " + smtpAddress + " (" + smtpPort + ") - SSL=" + smtpSSLEnabled + ". Usuario: " + smtpUser);

                //    if (Convert.ToBoolean(smtpSSLEnabled) == true)
                //    {                 
                //        Logger.Instance.Info(this,"Conectando con SSL");
                //        smtp.Connect(smtpAddress, Convert.ToInt32(smtpPort));
                //        smtp.StartTLS();
                //        smtp.Login(smtpUser, smtpPassword);


                //    }
                //    else
                //    {                     
                //        Logger.Instance.Info(this,"Conectando sin SSL");
                //        smtp.Connect(smtpAddress, Convert.ToInt32(smtpPort), Convert.ToBoolean(smtpSSLEnabled));  // or ConnectSSL for SSL               
                //        smtp.UseBestLogin(smtpUser, smtpPassword);
                //    }

                //    Logger.Instance.Info(this,"Enviando mail ...");
                //    smtp.SendMessage(email);
                //    Logger.Instance.Info(this,"Cerrando sesion ...");
                //    smtp.Close();
                //}


              
            }
            catch (Exception ex)
            {               
                Logger.Instance.Fatal(this,"Excepcion enviando mail: " + ex.Message);
            }

            return boolResult;
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblMailingError.Text = String.Empty;
                lblMailingError.Visible = false;

                Customer newCustomer = Facade.Instance.GenerateMemoryCustomer(TextBoxMail.Text, TextBoxProspectName.Text, TextBoxMail.Text, "Surname", TextBoxPassword.Text);
                if (Facade.Instance.IsExistingCustomer(newCustomer) == true)
                {
                    Logger.Instance.Warn(this,"Un usuario ("+TextBoxProspectName.Text+") trato de enviar un mail que ya existía: "+TextBoxMail.Text);
                    lblMailingError.Text = "An user with that e-mail already exists. Try another e-mail";
                    lblMailingError.Visible = true;
                }
                else
                {
                    #region Create New Customer
                    newCustomer.Id = Facade.Instance.CreateCustomer(newCustomer);
                    if (newCustomer.Id == -1)
                    {
                        Logger.Instance.Fatal(this, "Error al crear Cliente");
                        lblMailingError.Text = "We couldn't create your profile (CE). Please contact us via e-mail";
                        lblMailingError.Visible = true;
                        return;
                    }
                    #endregion Create New Customer
                    Device device = Facade.Instance.GenerateMemoryDevice(DateTime.Now.Ticks.ToString(),"NoCodeYet");
                    device.Id = Facade.Instance.CreateDevice(device);
                    if (device.Id == -1)
                    {
                        Logger.Instance.Fatal(this, "Error al crear Dispositivo");
                        lblMailingError.Text = "We couldn't create your profile (DE). Please contact us via e-mail";
                        lblMailingError.Visible = true;
                        return;
                    }
                    Target targ = Facade.Instance.GenerateMemoryTarget(TextBoxMail.Text + DateTime.Now.Ticks.ToString(), newCustomer, device);
                    targ.Id = Facade.Instance.CreateTarget(targ);
                    if (targ.Id == -1)
                    {
                        Logger.Instance.Fatal(this, "Error al crear Blanco");
                        lblMailingError.Text = "We couldn't create your profile (TE). Please contact us via e-mail";
                        lblMailingError.Visible = true;
                        return;
                    }



                    if (this.SendMail(TextBoxMail.Text, "Controles y Seguimiento - Application Download Confirmation!") == true)
                    {
                        Transaction newTransaction = new Transaction();




                        #region Create Transaction
                        newTransaction.CustomerAssociated = newCustomer;
                        newTransaction.TargetAssociated = null;
                        newTransaction.UserAssociated = null;
                        newTransaction.Type = TransactionType.UserCreatedMailNotificationType;
                        newTransaction.Result = "00";
                        newTransaction.Date = DateTime.Now;
                        newTransaction.Value1 = DDLMobilePlatform.SelectedValue;
                        newTransaction.Value2 = DDLInfoSource.SelectedValue;
                        newTransaction.Id = Facade.Instance.CreateTransaction(newTransaction);
                        #endregion Create Transaction

                        #region Set Platform
                        #endregion
                        Response.Redirect("~/Mailing/MailSentOk.aspx");
                    }
                    else
                    {
                        Logger.Instance.Fatal(this, "Error al enviar mail de creación de usuario");
                        lblMailingError.Text = "An error occurred when sending the mail. Please check the log";
                        lblMailingError.Visible = true;
                    }
                }
            }
        }
    }
}